package com.miplus.ccrm.core.service.commission;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.core.controller.vo.commission.*;
import com.miplus.ccrm.core.mapper.FiAgentRepayReportMapper;
import com.miplus.ccrm.core.pojo.FiAgentRepayReport;
import com.miplus.ccrm.core.pojo.FiBillReport;
import com.miplus.ccrm.core.pojo.FiCommissionAmt;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.commission.FiCommissionAmtService;
import com.miplus.ccrm.core.mapper.FiCommissionAmtMapper;
import com.miplus.ccrm.core.service.crd.FiImportHistService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
* @author wangzl
* @description 针对表【fi_commission_amt(催收佣金表)】的数据库操作Service实现
* @createDate 2025-03-11 22:06:53
*/
@Service
@Slf4j
public class FiCommissionAmtServiceImpl extends MPJBaseServiceImpl<FiCommissionAmtMapper, FiCommissionAmt>
    implements FiCommissionAmtService{

    @Resource
    FiAgentRepayReportMapper fiAgentRepayReportMapper;

    @Resource
    private ExportService exportService;
    @Resource
    private FiImportHistService fiImportHistService;

    @Override
    public IPage<CommissionAmtResVo> getCommissionAmtList(CommissionAmtListReqVo para)
    {
        return selectJoinListPage(
                new Page<>(para.getPageNum(),para.getPageSize()),
                CommissionAmtResVo.class,
                new MPJLambdaWrapper<FiCommissionAmt>()
                        .in(para.getDept()!=null,FiCommissionAmt::getSendtodept,para.getDept())
                        .in(para.getDisttag()!=null,FiCommissionAmt::getDisttag,para.getDisttag())
                        .eq(StringUtils.isNotEmpty(para.getBillMonth()),FiCommissionAmt::getBillMonth,para.getBillMonth())
                        .eq(ObjectUtils.isNotNull(para.getBillStatus()),FiCommissionAmt::getBillStatus,para.getBillStatus())
                        .selectAll(FiCommissionAmt.class)
                        .selectAs("(select grpname from sys_grp where grpid = t.sendtodept)",CommissionAmtResVo::getSendtodeptname)
                        .selectAs("fun_getnames('SORTING.QUEUE',t.disttag)",CommissionAmtResVo::getDisttagdesc)
                        .selectAs("case when t.bill_status = 1 then '已结账' else '未结账' end",CommissionAmtResVo::getBillStatusDesc)
                        .selectAs("fun_getnames('COMMISSION.RULE',t.commission_rule)",CommissionAmtResVo::getCommissionRuleDesc)
        );
    }
    @Override
    @Transactional
    public CmdResVo refreshReport(String usrid,String billMonth)
    {
        try {
            //获取当前催员结算的最后记录时间。
            String refreshMonth = billMonth;
            if(StringUtils.isEmpty(billMonth)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                refreshMonth = sdf.format( new Date());
            }
            log.info("commissionAmtRpt.更新佣金记录..." + refreshMonth);

            FiAgentRepayReport fiAgentRepayReport = fiAgentRepayReportMapper.selectOne(
                    new LambdaQueryWrapper<FiAgentRepayReport>()
                            .eq(FiAgentRepayReport::getBillMonth,refreshMonth)
                            .orderByDesc(FiAgentRepayReport::getStatisticsDate)
                            .last("limit 1")
            );
            if(fiAgentRepayReport == null)
            {
                log.info("commissionAmtRpt.没有找到催员佣金记录: 催收月份" + refreshMonth);
                return new CmdResVo(0,"没有找到催员佣金记录"+refreshMonth);
            }
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            String statisticsdate = sdf2.format(fiAgentRepayReport.getStatisticsDate());
            log.info("commissionAmtRpt.更新佣金记录...月份:{}, 日期:{}",refreshMonth, statisticsdate);
            Long ret = baseMapper.updateCommissionAmt(usrid, refreshMonth, statisticsdate);
            baseMapper.updateCommissionByAgent(usrid, refreshMonth);
            log.info("commissionAmtRpt.更新佣金记录：" + ret);
            return new CmdResVo(0,"更新成功" );
        }catch(Exception e)
        {
            log.error(" commissionAmtRpt refresh Report exception: " + e );
            return new CmdResVo(-1,"Exception :" +e);
        }
    }

    @Override
    public CmdResVo adjustCommissionAmt(String usrid, AdjustAmtVo para)
    {
        if(para == null || ObjectUtils.isNull(para.getReportId()))
            return new CmdResVo(-1,"没有指定结算ID参数");

        FiCommissionAmt fiCommissionAmt = getById(para.getReportId());
        if(fiCommissionAmt == null)
            return new CmdResVo(-1,"结算ID不存在");

        if( ObjectUtils.isNotNull(fiCommissionAmt.getBillStatus()) &&
                fiCommissionAmt.getBillStatus() == 1)
            return new CmdResVo(-1,"已结账，不能修改");
        BeanUtils.copyProperties(para, fiCommissionAmt);
        fiCommissionAmt.setMddt(new Date());
        fiCommissionAmt.setMdusr(usrid);
        updateById(fiCommissionAmt);
        return new CmdResVo(1,"更新成功");
    }

    @Override
    public CmdResVo saveAsExcel(String usrid, CommissionAmtListReqVo paras, HttpServletResponse response) {

        int pagesize = paras.getPageSize();
        if (pagesize > JPubUtils.exportMaxCount) {
            paras.setPageSize(JPubUtils.exportMaxCount);
        }

        IPage<CommissionAmtResVo> pages=getCommissionAmtList(paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"催收佣金统计表");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );

        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }

        return resVo;
    }
}




